/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.fimuni.pa165.frontend;

import cz.fimuni.pa165.backendapi.dto.CompanyDTO;
import cz.fimuni.pa165.backendapi.dto.EmployeeDTO;
import cz.fimuni.pa165.backendapi.dto.ReservationDTO;
import cz.fimuni.pa165.backendapi.facade.ServiceFacade;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author Michal
 */
@Controller
public class EmployeeController {

    @Autowired
    private ServiceFacade facade;

    @RequestMapping(value = "/employees")
    public String employeeHome(Model model) {
        List<EmployeeDTO> list = facade.getAllEmployees();
        model.addAttribute("employees", list);
        List<CompanyDTO> list2 = facade.getAllCompanies();
        model.addAttribute("companies", list2);
        if (list2.isEmpty()) {
            model.addAttribute("errMessage", "employeelist.errorMessage");

        }
        return "employee/list";
    }

    @RequestMapping(value = "/employeeAdd")
    public String addEmployee(@RequestParam(value = "input1") String input1,
            @RequestParam(value = "input2") String input2,
            @RequestParam(value = "date") String date,
            @RequestParam(value = "input5") String input5,
            @RequestParam(value = "input6") String input6,
            @RequestParam(value = "input7") String input7,
            @RequestParam(value = "input8") String input8,
            @RequestParam(value = "input4", required = false) String input4,
            Model model) {
        boolean valid = true;
        boolean companyCreated = true;
        List<CompanyDTO> list = facade.getAllCompanies();
        if (list.isEmpty()) {
            companyCreated = false;
            valid = false;
            model.addAttribute("errMessage", "employeelist.errorMessage");
            return employeeHome(model);
        }
        if (valid && (input1.equals("") || (input1.trim().length() == 0)) && companyCreated) {
            model.addAttribute("errMessage", "employeelist.errorMessage1");
            valid = false;
        }
        if (valid && (input2.equals("") || (input2.trim().length() == 0)) && companyCreated) {
            model.addAttribute("errMessage1", "employeelist.errorMessage2");
            valid = false;
        }
        java.util.Date utilDate = null;
        if (valid && companyCreated) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            dateFormat.setLenient(false);
            try {
                utilDate = dateFormat.parse(date);
            } catch (Exception ex) {
                model.addAttribute("errMessage2", "employeelist.errorMessage3");
                valid = false;
            }
        }
        List<EmployeeDTO> employees = facade.findEmployeeByUsername(input5);
        if (valid && employees.size() != 0){
            model.addAttribute("errMessage5", "employeelist.existingusername");
            valid = false;
        }
        if (valid && (input5.equals("") || (input5.trim().length() == 0)) && companyCreated) {
            model.addAttribute("errMessage5", "employeelist.errorMessage5");
            valid = false;
        }
        if (valid && (input6.equals("") || (input6.trim().length() == 0)) && companyCreated) {
            model.addAttribute("errMessage6", "employeelist.errorMessage6");
            valid = false;
        }
        if (valid) {
            EmployeeDTO emp = new EmployeeDTO();
            emp.setName(input1);
            emp.setSurname(input2);
            Date datum = new java.sql.Date(utilDate.getTime());
            emp.setBirthDate(datum);
            emp.setUsername(input5);
            emp.setPassword(input6);
            if (input7.equals("1")) {
                emp.setAuthority("ROLE_USER");
            } else {
                emp.setAuthority("ROLE_ADMIN");
            }
            if (input8.equals("1")) {
                emp.setEnabled(true);
            } else {
                emp.setEnabled(false);
            }
            Long temp = Long.parseLong(input4);
            CompanyDTO comp = facade.getCompanyById(temp);
            emp.setCompany(comp);
            facade.addEmployee(emp);
            model.addAttribute("infoMessage", "employeelist.confirmation");
        }
        return employeeHome(model);
    }

    @RequestMapping(value = "/employeeDelete")
    public String deleteEmployee(@RequestParam(value = "id") String id,
            Model model) {
        EmployeeDTO emp = facade.getEmployeeById(Long.parseLong(id));
        List<ReservationDTO> reservations = facade.getReservationByEmployee(emp);
        for (int i = 0; i < reservations.size(); i++){
            facade.removeReservation(reservations.get(i));
        }
        facade.removeEmployee(emp);
        return employeeHome(model);
    }

    @RequestMapping(value = "/employeeEditJSP/{id}")
    public String employeeEditJSP(@PathVariable(value="id") String id,
            Model model,
            HttpServletRequest request) {
        long l = 0;
        try {
            l = Long.parseLong(id);
        } catch (Exception ex) {
            if (id.equals("j_spring_security_logout")){
                return "redirect:/j_spring_security_logout";
            } else {
                return employeeHome(model);
            }
        }
        EmployeeDTO emp = facade.getEmployeeById(l);
        model.addAttribute("employee", emp);
        List<CompanyDTO> list = facade.getAllCompanies();
        model.addAttribute("companies", list);
        model.addAttribute("editerrMessage1", (String) request.getSession().getAttribute("editerrMessage1"));
        request.getSession().removeAttribute("editerrMessage1");
        model.addAttribute("editerrMessage2", (String) request.getSession().getAttribute("editerrMessage2"));
        request.getSession().removeAttribute("editerrMessage2");
        model.addAttribute("editerrMessage3", (String) request.getSession().getAttribute("editerrMessage3"));
        request.getSession().removeAttribute("editerrMessage3");
        model.addAttribute("editerrMessage4", (String) request.getSession().getAttribute("editerrMessage4"));
        request.getSession().removeAttribute("editerrMessage4");
        model.addAttribute("editerrMessage5", (String) request.getSession().getAttribute("editerrMessage5"));
        request.getSession().removeAttribute("editerrMessage5");
        return "employee/edit";
    }

    @RequestMapping(value = "/employeeEdit")
    public String employeeEdit(@RequestParam(value = "id") String id,
            @RequestParam(value = "name") String name,
            @RequestParam(value = "surname") String surname,
            @RequestParam(value = "date") String date,
            @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "authority") String authority,
            @RequestParam(value = "enabled") String enabled,
            @RequestParam(value = "input4", required = false) String input4,
            Model model,
            HttpServletRequest request) {
        boolean valid = true;
        if (name.equals("")) {
            request.getSession().setAttribute("editerrMessage1", "employeeedit.errorMessage1");
            valid = false;
            return "redirect:/employeeEditJSP/"+id;
        }
        if (surname.equals("")) {
            request.getSession().setAttribute("editerrMessage2", "employeeedit.errorMessage2");
            valid = false;
            return "redirect:/employeeEditJSP/"+id;
        }
        List<EmployeeDTO> employees = facade.findEmployeeByUsername(username);
        if ((employees.size() != 0) && (!employees.get(0).getName().equals(username))) {
            model.addAttribute("errMessage5", "employeelist.existingusername");
            valid = false;
            return "redirect:/employeeEditJSP/"+id;
        }
        if (username.equals("")) {
            request.getSession().setAttribute("editerrMessage4", "employeeedit.errorMessage4");
            valid = false;
            return "redirect:/employeeEditJSP/"+id;
        }
        if (password.equals("")) {
            request.getSession().setAttribute("editerrMessage5", "employeeedit.errorMessage5");
            valid = false;
            return "redirect:/employeeEditJSP/"+id;
        }
        java.util.Date utilDate = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        try {
            utilDate = dateFormat.parse(date);
        } catch (Exception ex) {
            request.getSession().setAttribute("editerrMessage3", "employeeedit.errorMessage3");
            valid = false;
            return "redirect:/employeeEditJSP/"+id;
        }
        if (valid) {
            EmployeeDTO emp = new EmployeeDTO();
            emp.setId(Long.parseLong(id));
            emp.setName(name);
            emp.setSurname(surname);
            Date datum = new java.sql.Date(utilDate.getTime());
            emp.setBirthDate(datum);
            emp.setUsername(username);
            emp.setPassword(password);
            if (authority.equals("1")) {
                emp.setAuthority("ROLE_USER");
            } else {
                emp.setAuthority("ROLE_ADMIN");
            }
            if (enabled.equals("1")) {
                emp.setEnabled(true);
            } else {
                emp.setEnabled(false);
            }
            Long temp = Long.parseLong(input4);
            CompanyDTO comp = facade.getCompanyById(temp);
            emp.setCompany(comp);
            facade.updateEmployee(emp);
            model.addAttribute("infoMessage", "employeeedit.infomessage");
        }
       return employeeHome(model); 
    }
    
    @RequestMapping(value = "/employeeFind")
    public String employeeFindJSP(@RequestParam(value = "hladanepriezvisko") String hladanepriezvisko,
            Model model){
        if (hladanepriezvisko.equals("") || (hladanepriezvisko.trim().length() == 0)){
            model.addAttribute("hladane", "employeelist.errzlehladane");
            return employeeHome(model);
        }
        List<EmployeeDTO> employees = facade.findEmployeeByName(hladanepriezvisko);
        if (employees.isEmpty()){
            model.addAttribute("infoMessage", "employeelist.nenajdene");
            return employeeHome(model);
        } else {
            model.addAttribute("employees", employees);
            return "employee/find";
        }
                                 
        
    }
}
